package com.snoopy.gas1.controller;

import com.snoopy.gas1.entity.Employee_info;
import com.snoopy.gas1.service.Employee_infoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.util.List;

@Controller
@RequestMapping("employee_info")
public class Employee_infoController {

    @Autowired
    private Employee_infoService employeeInfoService;

    // 列表查询（支持搜索）
    @GetMapping("/list")
    public String list(
            @RequestParam(value = "name", required = false) String name,
            Model model) {
        List<Employee_info> employeeLists;
        if (name != null && !name.trim().isEmpty()) {
            employeeLists = employeeInfoService.searchByName(name);
        } else {
            employeeLists = employeeInfoService.lists();
        }
        model.addAttribute("employeeLists", employeeLists);
        return "employee_info/list";
    }

    // 跳转到新增页面
    @GetMapping("/add")
    public String toAdd(Model model) {
        model.addAttribute("employee", new Employee_info());
        return "employee_info/add";
    }

    // 处理新增提交
    @PostMapping("/save")
    public String save(Employee_info employee, Model model) {
        try {
            employeeInfoService.add(employee);
            return "redirect:/employee_info/list";
        } catch (RuntimeException e) {
            model.addAttribute("errorMsg", e.getMessage());
            model.addAttribute("employee", employee);
            return "employee_info/add";
        }
    }

    // 跳转到编辑页面
    @GetMapping("/edit/{id}")
    public String toEdit(@PathVariable int id, Model model) {
        model.addAttribute("employee", employeeInfoService.getById(id));
        return "employee_info/edit";
    }

    // 处理编辑提交
    @PostMapping("/update")
    public String update(Employee_info employee, Model model) {
        try {
            employeeInfoService.update(employee);
            return "redirect:/employee_info/list";
        } catch (RuntimeException e) {
            model.addAttribute("errorMsg", e.getMessage());
            model.addAttribute("employee", employee);
            return "employee_info/edit";
        }
    }

    // 删除
    @GetMapping("/delete")
    public String delete(int id, RedirectAttributes redirectAttributes) {
        try {
            employeeInfoService.deleteById(id);
            redirectAttributes.addFlashAttribute("successMsg", "删除成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMsg", "删除失败：" + e.getMessage());
        }
        return "redirect:/employee_info/list";
    }
}